package com.jiegui.sms.service.impl;

import java.util.List;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jiegui.common.enums.CheckStatus;
import com.jiegui.common.exception.user.RRException;
import com.jiegui.common.utils.DateUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;
import javax.validation.Valid;

import com.jiegui.sms.domain.SmsTemplate;
import com.jiegui.sms.model.AppInfoModel;
import com.jiegui.sms.model.SendSmsModel;
import com.jiegui.sms.model.YunPianSendSmsVo;
import com.jiegui.sms.model.YunPianTplVo;
import com.jiegui.sms.service.SmsTemplateService;
import com.jiegui.system.service.ISystemConfigService;
import com.jiegui.utils.SmsHttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.jiegui.sms.mapper.SmsInterfaceRequestMapper;
import com.jiegui.sms.domain.SmsInterfaceRequest;
import com.jiegui.sms.service.SmsInterfaceRequestService;

/**
 * 短信发送记录Service业务层处理
 *
 * @author wuqicheng
 * @date 2021-12-30
 */
@Service
@Slf4j
public class SmsInterfaceRequestServiceImpl extends ServiceImpl<SmsInterfaceRequestMapper, SmsInterfaceRequest> implements SmsInterfaceRequestService {
    @Resource
    private SmsInterfaceRequestMapper smsInterfaceRequestMapper;

    @Resource
    SmsTemplateService smsTemplateService;


    @Resource
    ISystemConfigService systemConfigService;

    /**
     * 查询短信发送记录
     *
     * @param id 短信发送记录主键
     * @return 短信发送记录
     */
    @Override
    public SmsInterfaceRequest selectSmsInterfaceRequestById(Long id) {
        return smsInterfaceRequestMapper.selectById(id);
    }

    /**
     * 查询短信发送记录列表
     *
     * @param smsInterfaceRequest 短信发送记录
     * @return 短信发送记录
     */
    @Override
    public List<SmsInterfaceRequest> selectSmsInterfaceRequestList(SmsInterfaceRequest smsInterfaceRequest) {
        return smsInterfaceRequestMapper.selectSmsInterfaceRequestList(smsInterfaceRequest);
    }

    /**
     * 新增短信发送记录
     *
     * @param smsInterfaceRequest 短信发送记录
     * @return 结果
     */
    @Override
    public int insertSmsInterfaceRequest(SmsInterfaceRequest smsInterfaceRequest) {
        return smsInterfaceRequestMapper.insert(smsInterfaceRequest);
    }

    /**
     * 修改短信发送记录
     *
     * @param smsInterfaceRequest 短信发送记录
     * @return 结果
     */
    @Override
    public int updateSmsInterfaceRequest(SmsInterfaceRequest smsInterfaceRequest) {

        return smsInterfaceRequestMapper.updateById(smsInterfaceRequest);
    }

    /**
     * 批量删除短信发送记录
     *
     * @param ids 需要删除的短信发送记录主键
     * @return 结果
     */
    @Override
    public int deleteSmsInterfaceRequestByIds(Long[] ids) {
        return smsInterfaceRequestMapper.delete(new LambdaQueryWrapper<SmsInterfaceRequest>().in(SmsInterfaceRequest::getId, ids));
    }

    /**
     * 删除短信发送记录信息
     *
     * @param id 短信发送记录主键
     * @return 结果
     */
    @Override
    public int deleteSmsInterfaceRequestById(Long id) {
        return smsInterfaceRequestMapper.deleteById(id);
    }

    @Override
    public YunPianSendSmsVo sendSms(@Valid SendSmsModel sendSmsDto) throws RRException {
        SmsInterfaceRequest smsInterfaceRequest = new SmsInterfaceRequest();
        smsInterfaceRequest.setCreateTime(DateUtils.getTime());
        smsInterfaceRequest.setRecipientMobile(sendSmsDto.getMobile());

        sendSmsDto.setMobile("+86" + sendSmsDto.getMobile());

        // 获取短信应用配置
        AppInfoModel appInfo =systemConfigService.getConfigObject("yunPianConfig",AppInfoModel.class,true);
        if (appInfo == null) {
            throw new RRException("短信配置不存在");
        }

        smsInterfaceRequest.setApikey(appInfo.getAppKey());
        // 获取短信模板， 并替换参数, 生成要发送短信的实际消息
        SmsTemplate smsTemplate = smsTemplateService.getOne(new QueryWrapper<SmsTemplate>().eq("template_code", sendSmsDto.getTemplateCode()));

        if (!CheckStatus.SUCCESS.equals(smsTemplate.getCheckStatus())) {
            YunPianTplVo result =null;
            try {
                result=    SmsHttpUtils.tplGet(appInfo.getAppKey(), smsTemplate.getTplId());
                smsInterfaceRequest.setResultContext(JSON.toJSONString(result));
                if (result.getCode() != 0) {
                    throw new RRException("短信发送失败");
                }
                smsTemplate.setCheckStatus(result.getCheck_status().toString());
                smsTemplate.setTplId(result.getTpl_id());
                smsTemplate.setReason(result.getReason());
                smsTemplateService.saveOrUpdate(smsTemplate);
                smsTemplate = smsTemplateService.getById(smsTemplate.getId());
            }catch (Exception e){
                smsInterfaceRequest.setResCode("ERROR");
                smsInterfaceRequest.setResMsg(result.getMsg());
                smsInterfaceRequest.setText(JSON.toJSONString(sendSmsDto));
                smsInterfaceRequestMapper.insert(smsInterfaceRequest);
                throw new RRException("短信发送失败");
            }
        }

        if (smsTemplate == null) {
            throw new RRException("短信模板不存在");
        }

        if (!CheckStatus.SUCCESS.toString().equals(smsTemplate.getCheckStatus())) {
            throw new RRException("短信模板未审核通过");
        }
        String text = smsTemplate.getTemplateText();
        if (sendSmsDto.getParams().size() > 0) {
            for (String param : sendSmsDto.getParams()) {
                text = text.replaceFirst("#content#", param);
            }
        }
        smsInterfaceRequest.setText(text);
        // 新增短信请求记录
       smsInterfaceRequestMapper.insert(smsInterfaceRequest);
        try {
            // 发送短信请求
            YunPianSendSmsVo result = SmsHttpUtils.send(appInfo.getAppKey(), text, sendSmsDto.getMobile());
            // 更新短信请求记录
            smsInterfaceRequest.setResCode(result.getCode().toString());
            smsInterfaceRequest.setResMsg(result.getMsg());
            smsInterfaceRequest.setCount(result.getCount());
            smsInterfaceRequest.setFee(result.getFee());
            smsInterfaceRequest.setSid(result.getSid());
            smsInterfaceRequestMapper.updateById(smsInterfaceRequest);
            log.info("--------短信发生成功" + smsInterfaceRequest.toString());
            if (result.getCode() != 0) {
                smsInterfaceRequest.setResultContext(JSON.toJSONString(result));
                smsInterfaceRequestMapper.updateById(smsInterfaceRequest);
                throw new RRException("短信发送失败");
            }
            return result;
        } catch (Exception e) {
            log.error("发送短信失败: [{}]", e);
            return null;
        }
    }
}
